<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of admins
 *
 * @author Maulnick
 */
require_once 'document_entity.php';
class SPPB_entity extends Document_entity{
    public function load($id){
        // retrieve from database
        $result = array();
        $result['data'] = $this->get_sppb($id);
        $lineitems = $this->get_sppb_lineitem($result['data']->sppb_id);
        $container_details = array();
        foreach($lineitems as $lineitem){
            $container_detail = array();
            $container_detail = $lineitem;
            array_push($container_details, $container_detail);
        }
        $result['lineitem'] = $container_details;
        $this->set_data($result);
        return $this->get_data();
    }
    public function save(){
        // insert to database
        $data = $this->get_data();
        $sppb = $data['data'];
        // 1. insert sppb
        $step_1 = $this->db->insert('sppb',$sppb);
        if($step_1){
            $this->document_id = $this->get_last_id();
            foreach($data['lineitem'] as $container){
                // 2. insert sppb_lineitem
                $container['sppb_id'] = $this->document_id;
                $step_2 = $this->db->insert('sppb_lineitem', $container);
            }
        }
        return $step_1 && $step_2;
    }
    
    private function get_last_id(){
        //get last index sppb
        $this->db->select('sppb_id');
        $this->db->order_by('sppb_id', 'DESC');
        $this->db->limit(1);
        $result = $this->db->get('sppb');
        if($result->num_rows==1){
            return $result->row(0)->sppb_id;
        }else{
            return false;
        }
    }
    private function get_last_id_container(){
        //get last index sppb
        $this->db->select('sppb_lineitem_id');
        $this->db->order_by('sppb_lineitem_id', 'DESC');
        $this->db->limit(1);
        $result = $this->db->get('sppb_lineitem');
        if($result->num_rows==1){
            return $result->row(0)->sppb_lineitem_id;
        }else{
            return false;
        }
    }
    private function get_sppb($sppb_id){
        // get sppb
        $this->db->where('sppb_id',$sppb_id);
        $result = $this->db->get('sppb');
        if($result->num_rows==1){
            return $result->row(0);
        }else{
            return false;
        }
    }
    private function get_sppb_lineitem($sppb_id){
        // get sppb_lineitem
        $this->db->where('sppb_id',$sppb_id);
        $result = $this->db->get('sppb_lineitem');
        if($result->num_rows>0){
            return $result->result();
        }else{
            return false;
        }
    }
}